import React from 'react'
// @ts-ignore
import reactCSS from 'reactcss'
// @ts-ignore
import { SketchPicker } from 'react-color'

interface props{
    toolColor:any;
    setTooloColor:(color:any)=>void;
}

interface state{
    displayColorPicker?:boolean;
    color?:any;
}

class SketchColor extends React.Component<props,state> {
    constructor(props:any){
        super(props)
    }

    state={
        displayColorPicker: false,
        color:{
            r: '',
            g: '',
            b: '',
            a:'',
        }
    }

    componentDidUpdate(prevProps: Readonly<props>, prevState: Readonly<state>, snapshot?: any) {
        if(prevProps.toolColor != this.props.toolColor){
            this.setState({
                color:this.props.toolColor.rgb || this.props.toolColor
            })
        }
    }

    componentDidMount() {
        this.setState({
            color:this.props.toolColor
        })
    }

    handleClick = () => {
        // @ts-ignore
        this.setState({ displayColorPicker: !this.state.displayColorPicker })
    };

    handleClose = () => {
        this.setState({ displayColorPicker: false })
    };

    handleChange = (color:any) => {
        this.setState({ color: color.rgb })
        this.props.setTooloColor(color)
    };

    render() {
        // const {toolColor}=this.props
        const { color } = this.state;
        const styles = reactCSS({
            'default': {
                color: {
                    width: '36px',
                    height: '14px',
                    borderRadius: '2px',
                    background: `rgba(${ color.r }, ${ color.g }, ${ color.b }, ${ color.a })`,
                },
                swatch: {
                    padding: '5px',
                    background: '#fff',
                    borderRadius: '1px',
                    boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
                    display: 'inline-block',
                    cursor: 'pointer',
                },
                popover: {
                    position: 'absolute',
                    zIndex: '2',
                },
                cover: {
                    position: 'fixed',
                    top: '0px',
                    right: '0px',
                    bottom: '0px',
                    left: '0px',
                },
            },
        });

        return (
            <div>
                <div style={ styles.swatch } onClick={ this.handleClick }>
                    <div style={ styles.color } />
                </div>
                { this.state.displayColorPicker ? <div style={ styles.popover }>
                    <div style={ styles.cover } onClick={ this.handleClose }/>
                    <SketchPicker color={ color } onChange={ this.handleChange } />
                </div> : null }

            </div>
        )
    }
}

export const ChooseColor = React.memo(SketchColor)

